package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class RecommendUserService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    public ResponseEntity queryTodyBest() {
        TodayBest todayBest = new TodayBest();
//        当前登录人
        Long toUserId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserApi.todayBest(toUserId);

//        如果没有推荐用户，应该给一个默认的用户
        if(recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L); //在这里是写死的  你可以做成随机的
            recommendUser.setScore(60.0); //这里的得分也是写死的
        }

//        假如说recommendUser不为空
//        根据recommendUser中的userId查询  userInfo
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        BeanUtils.copyProperties(userInfo,todayBest);
        if(userInfo.getTags()!=null){
            todayBest.setTags(userInfo.getTags().split(",")); //就是从UserInfo中 但是UserInfo中的tags是字符串这里要的是数据
        }
        todayBest.setFateValue(recommendUser.getScore().longValue()); //就是

        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity queryRecommendUserList(Integer page, Integer pagesize) {
        Long toUserId = UserHolder.getUserId();
        PageResult pageResult = recommendUserApi.queryRecommendUserList(page,pagesize,toUserId);

        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();

        if(CollectionUtils.isEmpty(recommendUserList)){
//            如果查不到结果，给一些默认值
            recommendUserList = buildDefaultRecommendUserList();

        }


//        把集合中的一个一个的RecommendUser再次转成我们需要的TodayBest

        List<TodayBest> todayBestList = new ArrayList<>();
        TodayBest todayBest = null;
        for (RecommendUser recommendUser : recommendUserList) {
            todayBest = new TodayBest();

            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            BeanUtils.copyProperties(userInfo,todayBest);
            if(userInfo.getTags()!=null){
                todayBest.setTags(userInfo.getTags().split(",")); //就是从UserInfo中 但是UserInfo中的tags是字符串这里要的是数据
            }
            todayBest.setFateValue(recommendUser.getScore().longValue()); //就是
            todayBestList.add(todayBest);
        }

        pageResult.setItems(todayBestList);

        return ResponseEntity.ok(pageResult);




    }

    private List<RecommendUser> buildDefaultRecommendUserList() {
        List<RecommendUser> recommendUserList = new ArrayList<>();
        RecommendUser recommendUser = null;
        for (long i = 0; i < 10; i++) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(i+1);
            recommendUser.setScore(RandomUtils.nextDouble(60,99));
            recommendUserList.add(recommendUser);
        }
//        做一个排序
/*        recommendUserList.sort(new Comparator<RecommendUser>() {
            @Override
            public int compare(RecommendUser o1, RecommendUser o2) {
                return  o2.getScore().intValue() - o1.getScore().intValue();
            }
        });*/
        recommendUserList.sort((o1,o2)->{
            return o2.getScore().intValue()-o1.getScore().intValue();
        });
        return recommendUserList;
    }

//    查询指定用户的详细信息
    public ResponseEntity queryPersonalInfo(Long userId) {

        UserInfo userInfo = userInfoApi.findById(userId);
        TodayBest todayBest = new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest);
        if(userInfo.getTags()!=null){
            todayBest.setTags(userInfo.getTags().split(",")); //就是从UserInfo中 但是UserInfo中的tags是字符串这里要的是数据
        }
//        还需要从推荐表中查询两个人的缘分值
        Long score = recommendUserApi.queryScore(userId,UserHolder.getUserId());
        todayBest.setFateValue(score); //就是两个人的缘分值

        return ResponseEntity.ok(todayBest);
    }

    @Reference
    private QuestionApi questionApi;

    public ResponseEntity strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
//        有可能这个人没有设置陌生人问题 如果没有就给一个默认的
        if(question==null){
            return ResponseEntity.ok("你喜欢C还是D?");
        }
        return   ResponseEntity.ok(question.getTxt());

    }

  /*  {
        "userId": "1",
        "nickname":"黑马小妹",
       "strangerQuestion": "你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
       "reply": "我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"
    }*/
    public ResponseEntity replyStrangerQuestions(Long strangerId, String reply) {

//        查询当前登录人的详细信息，为了获取昵称
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

//        查询陌生人问题
        Question question = questionApi.findByUserId(strangerId);
//        回复问题的消息需要通过环信发送出去，发送出去的时候有一个固定的格式   这个格式是 app程序员和后台程序员约定好的

        Map<String,String> messageMap = new HashMap<>();
        messageMap.put("userId",UserHolder.getUserId().toString()); //发送方的id
        messageMap.put("nickname",userInfo.getNickname()); //发送方的昵称
        messageMap.put("strangerQuestion",question==null?"你喜欢选C还是D?":question.getTxt()); //对方的问题
        messageMap.put("reply",reply); //对方的问题

//        把map转成字符串
        String message = JSON.toJSONString(messageMap);
        huanXinTemplate.sendMsg(strangerId.toString(),message);// 要发送给谁

        return ResponseEntity.ok(null);
    }

}
